--
-- Description: Script to save an operating system.
-- This includes inserting a new record in the OperatingSystems table
-- if the Operating System does not exist.
-- Returns the OperatingSystemID.
-- Date created: 2 May 2008
--

set ANSI_NULLS on
set QUOTED_IDENTIFIER on
go

--
-- drop the procedure if it exists and recreate it.
--
if exists
(
	select * 
	from sys.objects
	where object_id = object_id(N'[dbo].[saveOperatingSystem_sp]')
	and type in (N'P', N'PC')
)

begin
    drop procedure [dbo].[saveOperatingSystem_sp]
end
go

create procedure [dbo].[saveOperatingSystem_sp]
(
    @OperatingSystemName nvarchar(100)
	, @OperatingSystemVersion varchar(100)
)
as
begin
	--
	-- validate the @OperatingSystemName. It cannot be null or empty.
	--
	if (@OperatingSystemName is null or LEN(@OperatingSystemName) = 0)
	begin
		raiserror
		(
			N'@OperatingSystemName parameter cannot be null or empty.'
			, 10 -- severity
			, 1 -- state
		)
	end
	
	--
	-- validate the @OperatingSystemVersion. It cannot be null or empty.
	--
	if (@OperatingSystemVersion is null or LEN(@OperatingSystemVersion) = 0)
	begin
		raiserror
		(
			N'@OperatingSystemVersion parameter cannot be null or empty.'
			, 10 -- severity
			, 1 -- state
		)
	end

	declare @OperatingSystemID int

	--
	-- check if the operating system name and version exists in the table.
	--
	if not exists
	(
		select top 1 1
		from [dbo].[OperatingSystems]
		where OperatingSystemName = @OperatingSystemName
		and OperatingSystemVersion = @OperatingSystemVersion
	)
	begin
		--
		-- create a new record with the new operating sysem name and version.
		--
		insert into [dbo].[OperatingSystems]
		(
			OperatingSystemName
			, OperatingSystemVersion
		)
		values
		(
			@OperatingSystemName
			, @OperatingSystemVersion
		)
	end

	--
	-- get the operating system id for the operating system name and version.
	--
	select @OperatingSystemID = OperatingSystemID
	from [dbo].[OperatingSystems]
	where OperatingSystemName = @OperatingSystemName
	and OperatingSystemVersion = @OperatingSystemVersion

	--
	-- return the result.
	--
	return @OperatingSystemID
end
go

set ansi_nulls off
go
set quoted_identifier off
go
